/**
 * Vite configuration for building the App component as a library
 */

import babel from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import react from '@vitejs/plugin-react';
import {defineConfig} from 'vite';
import {resolve} from 'path';

import viteCopyExcalidrawAssets from './viteCopyExcalidrawAssets';

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    'process.env.NODE_ENV': JSON.stringify('production'),
    'process.env': JSON.stringify({}),
    global: 'globalThis',
  },
  build: {
    lib: {
      // 入口文件
      entry: resolve(__dirname, 'src/lib.tsx'),
      // 库名称（全局变量名）
      name: 'LexicalPlaygroundApp',
      // 输出文件名
      fileName: (format) => `lexical-playground-app.${format}.js`,
      // 支持的格式
      formats: ['es', 'umd']
    },
    rollupOptions: {
      // 外部化依赖，不打包到库中
      external: ['react', 'react-dom'],
      output: {
        // 为 UMD 构建提供全局变量
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM'
        }
      }
    },
    outDir: 'dist',
    sourcemap: true
  },
  optimizeDeps: {
    esbuildOptions: {
      target: 'es2022',
      treeShaking: true,
    },
  },
  plugins: [
    babel({
      babelHelpers: 'bundled',
      babelrc: false,
      configFile: false,
      exclude: '**/node_modules/**',
      extensions: ['jsx', 'js', 'ts', 'tsx', 'mjs'],
      plugins: [
        '@babel/plugin-transform-flow-strip-types',
      ],
      presets: [['@babel/preset-react', {runtime: 'automatic'}]],
    }),
    react(),
    ...viteCopyExcalidrawAssets(),
    commonjs({
      strictRequires: [/\/node_modules\/(react-dom|react)\/[^/]\.js$/],
    }),
  ],
});
